package com.gexiaobao.pigeon.ui.fragment.match.training

import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.model.bean.PigeonBean
import com.gexiaobao.pigeon.app.model.param.SignUpParams
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentReleaseSignUpBinding
import com.gexiaobao.pigeon.ui.adapter.AddTrainingFlyAdapter
import com.gexiaobao.pigeon.viewmodel.TrainingInfoViewModel
import com.kingja.loadsir.core.LoadService
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat

/**
 * @Author      : hxw
 * @Date        : 2023/6/1 10:58
 * @Describe    : 训放赛报名
 */
class FragmentTrainingSignUp : BaseFragment<TrainingInfoViewModel, FragmentReleaseSignUpBinding>() {

    private var signUpStatus: Int = 0
    private var passId: Int = 0
    private var mType = ""

    private lateinit var loadsir: LoadService<Any>
    private val mAdapter: AddTrainingFlyAdapter by lazy { AddTrainingFlyAdapter(arrayListOf(),false) }
    private var pigeonData = ArrayList<PigeonBean.RingInfo>()
    private var invertList = ArrayList<PigeonBean.RingInfo>()
    private var muSelectedList = ArrayList<PigeonBean.RingInfo>()
    private val paramsList = arrayListOf<Int>()

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
        passId = arguments?.getString("passId")!!.toInt()
        signUpStatus = arguments?.getInt("signUpStatus")!!
        val title = requireArguments().getString("title")
        mType = requireArguments().getString("type").toString()
        if (title != null) {
            mDatabind.includeBar.toolbar.initClose(title) {
                nav().navigateUp()
            }
        }
    }

    override fun initData() {
        super.initData()
        // 1-显示报名，2-显示取消报名，3-不显示
        when (signUpStatus) {
            1 -> {
                mViewModel.signUp.set(getString(R.string.sign_up))
                mViewModel.isShowSignUp.set(true)
            }

            2 -> {
                mViewModel.signUp.set(getString(R.string.cancel_registration))
                mViewModel.isShowSignUp.set(true)
            }

            else -> {
                mViewModel.isShowSignUp.set(false)
            }
        }

        mDatabind.layoutList.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter).addItemDecoration(
            SpaceItemDecoration(0, Util.dp2px(context, 5f))
        )

        mDatabind.layoutList.swipeRefreshLayout.init {
            loadsir.showLoading()
            mViewModel.getPigeonList(true, "1")
        }

        //状态页配置
        loadsir = loadServiceInit(mDatabind.layoutList.swipeRefreshLayout) {
            //点击重试时触发的操作
            loadsir.showLoading()
            mViewModel.getPigeonList(true, "1")
        }

        mAdapter.addChildClickViewIds(R.id.train_fly_add_item_detail)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.train_fly_add_item_detail -> {
                    /** 跳转赛鸽详情页面 */
                    nav().navigateAction(R.id.action_to_pigeon_detail, Bundle().apply {
                        putString("pigeonId", pigeonData[position].pigeonId.toString())
                        putString("type", mType)
                        putBoolean("intentType", false)
                        putSerializable("pigeonData", pigeonData[position])
                    })
                }
            }
        }

        mAdapter.setOnMultipleChoiceClickListener(object :
            AddTrainingFlyAdapter.OnItemClickListener {
            override fun onItemClick(position: Int, list: List<PigeonBean.RingInfo>) {
                /** 保存点击item选中的条目 */
                muSelectedList.clear()
                muSelectedList.addAll(list)
                /** 循环选中的item放入实体类中 */
                paramsList.clear()
                list.forEach {
                    paramsList.addAll(listOf(it.pigeonId))
                }
            }
        })

    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        loadsir.showLoading()
        mViewModel.getPigeonList(true, "1")
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.llChooseAll, mDatabind.tvTrainingInfoGoSignUp) {
            when (it) {
                mDatabind.llChooseAll -> {
                    chooseAllItem()
                }

                mDatabind.tvTrainingInfoGoSignUp -> {
                    val userId = KvUtils.decodeString(Constant.USERID).toInt()
                    if (mViewModel.signUp.get() == "取消报名") {
                        val params = SignUpParams(
                            passId = passId,
                            userId = userId,
                            pIds = arrayListOf()
                        )
                        showLoading(getString(R.string.loading))
                        mViewModel.cancelTraining(params)
                    } else {
                        if (paramsList.size == 0 || paramsList.isEmpty()) {
                            RxToast.showToast(getString(R.string.choose_sign_pigeon))
                            return@setOnclickNoRepeat
                        }
                        val params = SignUpParams(
                            passId = passId,
                            userId = userId,
                            pIds = paramsList
                        )
                        showLoading(getString(R.string.loading))
                        mViewModel.getSignUpTraining(params)
                    }
                }
            }
        }
    }

    private fun chooseAllItem() {
        if (invertList.size == pigeonData.size) {
            //清除选中的条目
            invertList.clear()
            mAdapter.setClear()
            mDatabind.ivAddTrainingChecked.setImageResource(R.mipmap.unchecked)
        } else {
            /** 获取全选之后的list数据 */
            invertList = mAdapter.setInvertSelection() as ArrayList<PigeonBean.RingInfo>
            /** 新的；list保存全选的数据 是否全部选中 */
            muSelectedList.clear()
            muSelectedList.addAll(invertList)

            mDatabind.ivAddTrainingChecked.setImageResource(R.mipmap.checked)
            /** 循环选中的数据放入实体类中 */
            paramsList.clear()
            invertList.forEach {
                paramsList.addAll(listOf(it.pigeonId))
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.pigeonData.observe(viewLifecycleOwner) {
            if (!it.listData.isNullOrEmpty()) {
                pigeonData = it.listData
            }
            loadListData(it, mAdapter, loadsir, mDatabind.layoutList.swipeRecyclerView, mDatabind.layoutList.swipeRefreshLayout)
        }

        mViewModel.cancelTrainingResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                mViewModel.signUp.set(getString(R.string.sign_up))
                RxToast.showToast(getString(R.string.Registration_cancelled))
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }

        mViewModel.signUpTrainingResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                mViewModel.signUp.set(getString(R.string.cancel_registration))
                RxToast.showToast(getString(R.string.Registration_successful))
                nav().navigateUp()
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
    }
}